import axios from 'axios';
import {
	Message
} from 'element-ui';
import {
	Loading
} from 'element-ui';
import router from '../router/index'
// let loading
// function startLoading() {
//     loading = Loading.service({
//         lock: true,
//         text: '加载中...',
//         background: 'rgba(0, 0, 0, 0.1)'
//     })
// }
// function endLoading() {
//     loading.close()
// }
// let needLoadingRequestCount = 0
// export function showFullScreenLoading() {
//     if (needLoadingRequestCount === 0) {
//         startLoading()
//     }
//     needLoadingRequestCount++
// }
// export function tryHideFullScreenLoading() {
//     if (needLoadingRequestCount <= 0) return
//     needLoadingRequestCount--
//     if (needLoadingRequestCount === 0) {
//         endLoading()
//     }
// }
// 请求超时时间
axios.defaults.timeout = 60000;
// post请求头
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
// 请求拦截器
axios.interceptors.request.use(
	config => {
		config.data = {
			data: encodeURIComponent(JSON.stringify(config.data))
		}
		return config;
	},
	error => {
		return Promise.error(error);
	}
);
// 响应拦截器
axios.interceptors.response.use(
	response => {
		// tryHideFullScreenLoading()
		response.data = JSON.parse(decodeURIComponent(response.data))
		if (response.data.code === 200) {
			return Promise.resolve(response.data);
		} else {
			Message(response.data.msg)
		}
	},
	error => {
		// tryHideFullScreenLoading()
		if (error && error.response) {
			if (error.response.status == '401') {
				// Message('token失效请重新登录')
			}
		}
	}
);
/**
 * get方法，对应get请求
 */
const get = (url, params) => {
	return new Promise((resolve, reject) => {
		axios.get(url, {
			params: params
		}).then(res => {
			resolve(res.data);
		}).catch(err => {
			reject(err)
		})
	});
}

/**
 * post方法，对应post请求
 */
const post = (url, params = {}) => {
	return new Promise((resolve, reject) => {
		axios.post(url, params)
			.then(res => {
				resolve(res.data);
			})
			.catch(err => {
				reject(err)
			})
	});
}
/**
 * delete方法，对应delete请求
 */
const deleteUrl = (url, params) => {
	return new Promise((resolve, reject) => {
		axios.delete(url, {
				params: params
			})
			.then(res => {
				resolve(res.data);
			})
			.catch(err => {
				reject(err)
			})
	});
}
/**
 * put方法，对应put请求
 */
const put = (url, params) => {
	return new Promise((resolve, reject) => {
		axios.put(url, params)
			.then(res => {
				resolve(res.data);
			})
			.catch(err => {
				reject(err)
			})
	});
}

const postUrl = (url, params) => {
	return new Promise((resolve, reject) => {
		axios.post(url, params, {
				headers: {
					'Content-Type': 'multipart/form-data'
				}
			}).then(res => {
				resolve(res.data);
			})
			.catch(err => {
				reject(err)
			})
	});
}

export {
	get,
	post,
	put,
	deleteUrl,
	postUrl,
}